import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:music_app/api/mock_api.dart';
import 'package:music_app/controllers/audio_player_controller.dart';
import 'package:music_app/widget/list_song_item.dart';
import 'package:music_app/widget/my_cached_network_image.dart';

class DailyRecommendView extends StatefulWidget {
  const DailyRecommendView({super.key});

  @override
  State<DailyRecommendView> createState() => _DailyRecommendViewState();
}

class _DailyRecommendViewState extends State<DailyRecommendView> {
  int selectedIndex = 0;

  // 音乐播放控制方法
  final audioController = Get.find<AudioPlayerController>();
  // 数据列表
  List<dynamic> _songs = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getData();
    });
  }

  Future<void> getData() async {
    try {
      final response = await MockApi.fetchRecommendSongs();
      final List<dynamic> songs = response['data']['dailySongs'];
      setState(() {
        _songs = songs.toList(); // 只取前 9 条
      });
    } catch (e) {
      setState(() {
        _songs = []; // 只取前 9 条
      });
    } finally {}
  }

  Widget _buildToggleTabs() {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 12),
      padding: const EdgeInsets.all(4),
      decoration: BoxDecoration(
        color: const Color(0xFFEAEAEA),
        borderRadius: BorderRadius.circular(18),
      ),
      child: Row(
        children: List.generate(2, (index) {
          final isSelected = index == selectedIndex;
          return Expanded(
            child: GestureDetector(
              onTap: () {
                setState(() => selectedIndex = index);
              },
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 200),
                padding: const EdgeInsets.symmetric(vertical: 8),
                decoration: BoxDecoration(
                  color: isSelected ? Colors.white : null,
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Center(
                  child: Text(
                    index == 0 ? '默认推荐' : '风格推荐',
                    style: TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.bold,
                      color: isSelected ? Colors.black : Colors.grey[600],
                    ),
                  ),
                ),
              ),
            ),
          );
        }),
      ),
    );
  }

  Widget _buildSongItem(song) {
    return ListSongItem(
      id: song['id'],
      fee: song['fee'],
      imageUrl: song['al']['picUrl'],
      title: song['name'],
      artist: (song['ar'] as List)
          .map(
            (artist) => artist['name'],
          )
          .join(', '),
      onTap: () {
        audioController.playSong(song);
        // 你可以在这里实现点击事件
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (context, innerBoxIsScrolled) => [
          SliverAppBar(
            pinned: true,
            expandedHeight: 200,
            flexibleSpace: FlexibleSpaceBar(
              background: Stack(
                fit: StackFit.expand, // 设置除了定位组件外的组件为满屏 测试效果 设置了宽高也会满屏
                children: [
                  MyCachedNetworkImage(
                    imageUrl: _songs[0]['al']['picUrl'],
                    width: 120,
                    height: 120,
                    x: 480,
                    y: 480,
                  ),
                  // 高斯模糊效果
                  BackdropFilter(
                    filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
                    child: Container(color: Colors.black.withOpacity(0.7)),
                  ),
                  const Positioned(
                    bottom: 16,
                    left: 16,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '29/05',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 28,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(height: 4),
                        Text(
                          '查看今日运势 >',
                          style: TextStyle(color: Colors.white70),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            leading: IconButton(
              icon: const Icon(
                Icons.arrow_back,
              ),
              onPressed: () {
                Get.back();
              },
            ),
            actions: [
              IconButton(
                icon: const Icon(Icons.more_vert),
                onPressed: () {},
              ),
            ],
            title: _buildToggleTabs(),
          ),
          SliverPersistentHeader(
            pinned: true,
            delegate: _SliverPlayAllHeader(
              height: 56,
              child: Container(
                color: Colors.white,
                alignment: Alignment.centerLeft,
                height: 56,
                child: Row(
                  children: [
                    IconButton(
                      onPressed: () {},
                      icon: const Icon(
                        Icons.play_circle_fill,
                        color: Color(0xFFf43f3b),
                      ),
                    ),
                    const SizedBox(width: 8),
                    const Text(
                      '播放全部',
                      style: TextStyle(fontSize: 16),
                    ),
                    const SizedBox(width: 8),
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 6, vertical: 2),
                      decoration: BoxDecoration(
                        color: Colors.red.shade100,
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: const Text(
                        'VIP歌曲免费畅听',
                        style:
                            TextStyle(color: Color(0xFFf43f3b), fontSize: 12),
                      ),
                    )
                  ],
                ),
              ),
            ),
          ),
        ],
        body: selectedIndex == 0
            ? ListView.builder(
                padding: EdgeInsets.zero,
                itemCount: _songs.length,
                itemBuilder: (_, index) => _buildSongItem(_songs[index]),
              )
            : const Center(
                child: Text('风格推荐（待实现）'),
              ),
      ),
    );
  }
}

class _SliverPlayAllHeader extends SliverPersistentHeaderDelegate {
  final Widget child;
  final double height;

  _SliverPlayAllHeader({
    required this.child,
    this.height = 56,
  });

  @override
  double get minExtent => height;

  @override
  double get maxExtent => height;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return child;
  }

  @override
  bool shouldRebuild(covariant _SliverPlayAllHeader oldDelegate) {
    return oldDelegate.child != child || oldDelegate.height != height;
  }
}
